package risk.control.project.api;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import risk.control.project.config.constant.FilePath;
import risk.control.project.service.AuthCodeService;
import risk.control.project.utils.response.ResponseUtils;

import java.io.File;
import java.util.HashMap;
import java.util.UUID;


@RestController
public class MAIN_000_001_002 {
    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_001_002.class);

//    //文件夹
//    private static final String folderPath = "D:/publicFile/branch";

    private final AuthCodeService authCodeService;

    //文件上传下载前置接口，获取验证码
    public MAIN_000_001_002(AuthCodeService authCodeService) {
        this.authCodeService = authCodeService;
    }


    //网点文件上传
    @PostMapping(value = "main/000_001_002", produces = {"multipart/form-data"})
    //参数名需要与form表单中设置的 name属性值对应上，否则获取到的为null
    public String doPost(MultipartFile file, HttpServletRequest req) {
        //验证permit
        String authCode = req.getHeader("authCode");
        HashMap<String, String> map = authCodeService.verifyAuthCode(authCode);
        String state = map.get("state");
        if (!state.equals("000")) {
            String msg = map.get("msg");
            return ResponseUtils.generateFail(msg);
        }
        //1、处理创建文件夹
        File folder = new File(FilePath.UPLOAD_BRANCH_FOLDER);
        //不存在，则创建
        if (!folder.exists()) {
            boolean success = folder.mkdirs();
            if (success) {
                logger.error("创建文件夹成功");
            }
        }
        //2、处理文件名
        if (file == null) {
            return ResponseUtils.generateFail("上传失败，文件为空");
        }
        String oldName = file.getOriginalFilename();
        //获取文件后缀名
        if (oldName == null) {
            return ResponseUtils.generateFail("上传失败，文件名获取失败");
        }
        int index = oldName.lastIndexOf(".");
        if (index > 0) {
            String suffixName = oldName.substring(index);
            try {
                //文件保存
                String newName = UUID.randomUUID() + suffixName;
                file.transferTo(new File(folder, newName));
                logger.warn("上传成功，文件后缀名：{}", file.getName());
                return ResponseUtils.generateSucceed("上传成功");
            } catch (Exception e) {
                return ResponseUtils.generateFail("文件保存失败");
            }
        } else {
            return ResponseUtils.generateFail("上传失败，文件后缀名无效");
        }
    }


}
